//
//  SEGPublishEditCarViewModel.m
//  Commom
//
//  Created by 梁学彰 on 2020/6/5.
//

#import "SEGPublishEditCarViewModel.h"
#import "SEGPublishHouseViewModel.h"
#import "SEGRentalPriceManager.h"
#import "SEGImageChooseViewModel.h"
#import "SEGSaveorupdateleaseManager.h"

@implementation SEGPublishEditCarViewModel
#pragma mark - life cycle
- (instancetype)initWithrentalId:(NSString *)rentalId rentalType:(SEGEnumPublishCarType )rentalType {
    if (self = [super init]) {
        _rentalId = rentalId;
        _rentalType = rentalType;
        [self initData];
    }
    return self;
}

#pragma mark - init
- (void)initData {
    _requestParams = [NSMutableDictionary dictionary];
    _imageData = [NSArray array];
    _selectedData = [NSDictionary dictionary];
}

#pragma mark - send request
- (RACSignal *)loadCommonAndEditData {
    return [RACSignal concat:@[[self loadCommonData],[self loadData]]];
}

- (RACSignal *)loadCommonData {
    
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        if (!self.rentalId) {
            //新发布
            //获取社区所在的位置
            [[SEGHouseRentalAndSaleRequestManager new] requestRegionInfoWithCommunityId:kAccountCommunityID finished:^(id result, NSError *error) {
                if (!error) {
                    if ([result isKindOfClass:[NSDictionary class]]) {
                        self.regionName = result[@"data"][@"regionName"];
                    }
                }
                [subscriber sendCompleted];
            }];
        }else {
            //修改
            if (!(self.rentalId && self.rentalId.length > 0)) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"车位租售主键ID不能为空！"}]];
            }
            [self.requestParams setValue:self.rentalId forKey:@"rentalId"];
            [[SEGDetailsellManager sharedManager] requestCarRentalDetailLeaseWithRentalid:self.rentalId finished:^(BOOL isSuccessed, SEGCarRentalDetailsDataModel *model, NSString *codeType, NSString *errorMessage) {
                if (!isSuccessed) {
                    [subscriber sendError:[NSError errorWithDomain:errorMessage code:100 userInfo:nil]];
                }
                self.editModel = model;
                [subscriber sendCompleted];
            }];
            
        }
        
        return nil;
    }];
    return signal;

}

- (RACSignal *)loadData {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        
        /* 押金模式：parkingDeposit  车位类型：parkingType */
        [[SEGQuerydictlistManager sharedManager] requestQuerydictlistWithType:@"parkingDeposit,parkingType" finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:errorMessage code:100 userInfo:nil]];
            }
            SEGQuerydictlistModel *listModel = [SEGQuerydictlistModel yy_modelWithDictionary:result];
            
            // 对字典数据进行区分绑定
            NSMutableArray<SEGQuerydictlistDictlistModel*> *parkingType = [NSMutableArray array];
            NSMutableArray<SEGQuerydictlistDictlistModel*> *parkingDeposit = [NSMutableArray array];
            [listModel.data.dictList enumerateObjectsUsingBlock:^(SEGQuerydictlistDictlistModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.type isEqualToString:@"parkingType"]) [parkingType addObject:obj];
                if ([obj.type isEqualToString:@"parkingDeposit"]) [parkingDeposit addObject:obj];
            }];
            self.selectedData = @{@"parkingType":parkingType,@"parkingDeposit":parkingDeposit};
            
            NSMutableArray *arrRow1 = [NSMutableArray array];
            {
                {
                    SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                    data.title = @"所属区域";
                    data.placeholder = @"";
                    data.paraKey = @"CommunityName";
                    data.content = kAccountCommunityName;
                    if (self.regionName) {
                        data.content = [NSString stringWithFormat:@"%@%@",self.regionName,kAccountCommunityName];
                    }
                    if (self.editModel) {
                        data.content = [NSString stringWithFormat:@"%@%@",self.editModel.data.regionName,self.editModel.data.communityName];
                    }
                    
                    SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_NO_Edit];
                    [arrRow1 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
                }
                
                {
                    SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                    data.title = @"车位类型";
                    data.placeholder = @"请选择车位类型";
                    data.paraKey = @"ParkingType";
                    if (self.rentalId) {
                        //1露天车位 2:地上车库 3:地下车库
                        if ([self.editModel.data.parkingType isEqualToString:@"1"]) {
                            data.content = @"露天车位";
                        }else if ([self.editModel.data.parkingType isEqualToString:@"2"]) {
                            data.content = @"地上车库";
                        }else if ([self.editModel.data.parkingType isEqualToString:@"3"]) {
                            data.content = @"地下车库";
                        }
                        [self.requestParams setValue:self.editModel.data.parkingType forKey:@"parkingType"];
                    }
                    
                    SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_NO];
                    [arrRow1 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
                }
                
                {
                    SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                    data.title = @"面积";
                    data.content = @"m²";
                    data.paraKey = @"Area";
                    data.textFieldPlaceholder = @"请输入面积";
                    if (self.rentalId) {
                        data.content2 = self.editModel.data.area;
                        [self.requestParams setValue:self.editModel.data.area forKey:@"area"];
                    }
                    SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_TextField_DecimalPad];
                    [arrRow1 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
                }
                
                if (self.rentalType == SEGEnumPublishCarTypeCS) {
                    {
                        SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                        data.title = @"售价";
                        data.content = @"万";
                        data.textFieldPlaceholder = @"请输入期望售价";
                        data.paraKey = @"Price";
                        if (self.rentalId) {
                            NSString *price = [NSString stringWithFormat:@"%@",[SEGRentalPriceManager getPriceStringWithformatValue:self.editModel.data.price]];
                            data.content2 = price;
                            [self.requestParams setValue:price forKey:@"price"];
                        }
                        SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_TextField_DecimalPad];
                        [arrRow1 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
                    }
                }
            }
            
            NSMutableArray *arrRow2 = [NSMutableArray array]; {
                if (self.rentalType == SEGEnumPublishCarTypeZL) {
                    if (self.rentalId) {
                        NSString *price = [NSString stringWithFormat:@"%@",[SEGRentalPriceManager getPriceStringWithformatValue:self.editModel.data.price]];
                        [self.requestParams setValue:price forKey:@"price"];
                        [self.requestParams setValue:self.editModel.data.depositOption forKey:@"depositOption"];//按啥计价 1:按天计价
                    }
                    [arrRow2 addObject:@{@"Indetifier":@"SEGCarRentalSelectPriceTableViewCell"}];
                }
            }
            
            NSMutableArray *arrRow3 = [NSMutableArray array];
            {
                
                if (self.rentalType == SEGEnumPublishCarTypeZL) {
                    SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                    data.title = @"押金模式";
                    data.placeholder = @"请选择押金模式";
                    data.paraKey = @"DEPOSIT";
                    
                    if (self.rentalId) {
                        __block NSString *depositModeString = @"";
                        NSArray<SEGQuerydictlistDictlistModel*> *parkingDeposit = [self.selectedData valueForKey:@"parkingDeposit"];
                        [parkingDeposit enumerateObjectsUsingBlock:^(SEGQuerydictlistDictlistModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            if ([obj.code isEqualToString:self.editModel.data.depositMode]) {
                                depositModeString = obj.name;
                                *stop = YES;
                                return;
                            }
                        }];
                        data.content = depositModeString;
                        [self.requestParams setValue:self.editModel.data.depositMode forKey:@"depositMode"];
                    }
                    
                    SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_NO];
                    [arrRow3 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
                }
            }
            
            NSMutableArray *arrRow4 = [NSMutableArray array];
            {
                SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                data.title = @"标题";
                data.textFieldPlaceholder = @"如车位、价格、面积等";
                data.paraKey = @"TITLE";
                if (self.rentalId) {
                    data.content2 = self.editModel.data.rentalTitle;
                    [self.requestParams setValue:self.editModel.data.rentalTitle forKey:@"rentalTitle"];
                }
                SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_Title];
                [arrRow4 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
            }
            {
                SEGPublishHouseViewModel *data = [[SEGPublishHouseViewModel alloc]init];
                data.paraKey = @"CONTENT";
                data.textFieldPlaceholder = @"详细描述需要租售的车位信息";
                if (self.rentalId) {
                    data.content2 = self.editModel.data.rentalDesc;
                    [self.requestParams setValue:self.editModel.data.rentalDesc forKey:@"rentalDesc"];
                }
                SEGPublishHouseViewLayout *layout = [[SEGPublishHouseViewLayout alloc]initWithData:data type:SEGEnumPublishHouseViewType_Content];
                layout.limitTextLenght = 200;
                [arrRow4 addObject:@{@"Indetifier":SEGPublishHouseViewCellIndetifier,@"data":layout}];
            }
            
            NSMutableArray *arrRow5 = [NSMutableArray array];
            {
                SEGImageChooseViewModel *data = [[SEGImageChooseViewModel alloc]init];
                data.title = @"上传照片";
                data.desc = @"(最多9张)";
                
                __block NSMutableArray<NSString*> *urlArray = [NSMutableArray array];
                [[self.editModel.data.parkingPhoto componentsSeparatedByString:@","] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([obj length] > 0) [ urlArray addObject:obj];
                }];
                self.imageData = urlArray;
                SEGImageChooseViewLayout *layout = [[SEGImageChooseViewLayout alloc]initWithData:data type:SEGEnumImageChooseViewType_THREE];
                [arrRow5 addObject:@{@"Indetifier":SEGImageChooseViewCellIndetifier ,@"data":layout}];
            }
            
            
            
            
            
            self.dataSoure = @[arrRow1,arrRow2,arrRow3,arrRow4,arrRow5];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
    return signal;
}


- (RACSignal *)sendSaveImageRequestWithPhotos:(NSArray<UIImage *> *)photos {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        if (self.imageData.count >= 9) {
            [subscriber sendCompleted];
        }
        @weakify(self)
        [[SEGMultipartfileuploadManager sharedManager] requestMultipartfileuploadWithImage:photos progress:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            @strongify(self)
            if (isSuccessed) {
                NSMutableArray<NSString*> *arrM = [NSMutableArray arrayWithArray:self.imageData];
                NSArray *imagesArr = (NSArray*)[result valueForKey:@"data"];
                [arrM addObjectsFromArray:imagesArr];
                self.imageData = [NSArray arrayWithArray:arrM];
                [subscriber sendCompleted];
            }else {
                [subscriber sendError:[NSError errorWithDomain:errorMessage code:100 userInfo:nil]];
            }
        }];
        
        return nil;
    }];
    return signal;
}

- (RACSignal *)sendPublishEditCarRequest {
    @weakify(self);
    RACSignal *signal = [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        @strongify(self);
        if (self.rentalId) {
            //修改
            if (self.editModel) {
                if (self.editModel.data.communityId&&self.editModel.data.communityId.length > 0) {
                    [self.requestParams setValue:self.editModel.data.communityId forKey:@"communityId"];
                }
            }
        }else {
            //新增
            [self.requestParams setValue:kAccountCommunityID forKey:@"communityId"];
        }

        if (self.rentalType == SEGEnumPublishCarTypeCS) {
            //出售
            [self.requestParams setValue:@"6" forKey:@"rentalType"];
        }else {
            //租赁
            [self.requestParams setValue:@"5" forKey:@"rentalType"];
        }

        //车位类型
        if (![[self.requestParams allKeys] containsObject:@"parkingType"] || [[self.requestParams valueForKey:@"parkingType"] length] <= 0) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请选择车位类型"}]];
            return nil;
        }

        //面积
        if (![[self.requestParams allKeys] containsObject:@"area"] || [[self.requestParams valueForKey:@"area"] length] <= 0 || [[self.requestParams valueForKey:@"area"] floatValue] <= 0.001) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请输入面积"}]];
            return nil;
        }

        //价格
        if (![[self.requestParams allKeys] containsObject:@"price"] || [[self.requestParams valueForKey:@"price"] length] <= 0|| [[self.requestParams valueForKey:@"price"] floatValue] <= 0.001) {
            if (self.rentalType == SEGEnumPublishCarTypeCS) {
                //出售
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请输入售价"}]];
                
            }else {
                //租赁
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请输入租金"}]];
            }

            return nil;
        }

        if (self.rentalType == SEGEnumPublishCarTypeCS) {

        }else {
            //租赁
            //押金模式
            if (![[self.requestParams allKeys] containsObject:@"depositMode"] || [[self.requestParams valueForKey:@"depositMode"] length] <= 0) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请选择押金模式"}]];
                return nil;
            }
        }

        //标题
        if (![[self.requestParams allKeys] containsObject:@"rentalTitle"] || [[self.requestParams valueForKey:@"rentalTitle"] length] <= 0) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请输入标题"}]];
            return nil;
        }

        //详细描述
        if (![[self.requestParams allKeys] containsObject:@"rentalDesc"] || [[self.requestParams valueForKey:@"rentalDesc"] length] <= 0) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请填写详细描述"}]];
            return nil;
        }

        if ([[self.requestParams valueForKey:@"rentalDesc"] length] > 200) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"填写详细描述最长200字"}]];
            return nil;
        }


        //照片
        if (self.imageData.count <= 0) {
            [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"请上传车位图片"}]];
            return nil;
        }

        NSString *imageStr = [self.imageData componentsJoinedByString:@","];
        [self.requestParams setValue:imageStr forKey:@"parkingPhoto"];
        [self.requestParams setValue:@"2" forKey:@"publisherType"];
        [self.requestParams setValue:@"1" forKey:@"advisoryType"];
        [self.requestParams setValue:@"2" forKey:@"releaseType"];

        [subscriber sendNext:@(1)];
        [[SEGSaveorupdateleaseManager sharedManager] requestPulishEditWithParams:self.requestParams Finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            [subscriber sendNext:@(0)];
            if (!isSuccessed) {
                [subscriber sendError:[NSError errorWithDomain:NSURLErrorDomain code:100 userInfo:@{NSLocalizedDescriptionKey:@"提交失败，请稍后重试"}]];
                return;
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SEGUserCarRentalChangeNotification" object:nil];
            [subscriber sendCompleted];
        }];
        
        
        return nil;
    }];
    return signal;
}



#pragma mark - custom delegate

#pragma mark - system delegate

#pragma mark - event response

#pragma mark - private methods

#pragma mark - setter and getter
@end
